<?php

class RoleForm extends CFormModel {
	
	const CREATE = 'create';
	const UPDATE = 'update';
	
	public $isNew;
	public $name;
	public $description;
	public $operations;
	
	public function __construct()
	{
		$this->isNew = true;
		$this->operations = array();
	}
	
	public function rules() {
		return array (
			array ('name', 'required'),
			array ('description', 'required'),
			array ('name', 'checkNewRole', 'on' => self::CREATE),
			array ('name', 'checkExistingRole', 'on' => self::UPDATE)
		);
	}
	
	function checkNewRole($attribute,$params)
	{
		$name = $this->$attribute;
		$item = Yii::app()->authManager->getAuthItem($name);
		if ($item != null || isset($item))	
			$this->addError($attribute, Yii::t('user', 'A role or an operation named {name} exists', array('{name}'=>$name)));
	}

	function checkExistingRole($attribute,$params)
	{
		$name = $this->$attribute;
		$item = Yii::app()->authManager->getAuthItem($name);
		if ($item == null || !isset($item))	
			$this->addError($attribute, Yii::t('user', 'Can\'t find a role or an operation named {name}.', array('{name}'=>$name)));
		if ($item->type != CAuthItem::TYPE_ROLE)	
			$this->addError($attribute, Yii::t('user', 'Can\'t find a role named {name}', array('{name}'=>$name)));
	}

	public function attributeLabels() {
		return array (
			'name' => Yii::t('user', 'Name'),
			'description' => Yii::t('user', 'Description'),
			'operations' => Yii::t('user', 'Allowed Operations')
		);
	}

	public function load($authItem)
	{
		if ($authItem != null && $authItem->type == CAuthItem::TYPE_ROLE)
		{
			$this->isNew = false;
			$this->name = $authItem->name;
			$this->description = $authItem->description;
			$this->operations = array();
			
			foreach($authItem->children as $child)
			{
				$this->operations[$child->name] = $child->name;
				foreach ($child->getChildren() as $c)
				{
					$this->operations[$c->name] = $c->name;
				}
			}
			
		}
	}
	
	public function save() {
		if (!$this->hasErrors())
		{
			$role = Yii::app()->authManager->getAuthItem($this->name);
			if (!isset($role))
			{
				$role = Yii::app()->authManager->createAuthItem($this->name, CAuthItem::TYPE_ROLE, $this->description);
			}else{
				$role->description = $this->description;
				Yii::app()->authManager->saveAuthItem($role);
			}
			
			foreach ($this->operations as $operation=>$value)
			{
				if ($value === "0" || $value === 0 || $value === false)
				{
					Yii::app()->authManager->removeItemChild($role->name, $operation);
				} else if (!Yii::app()->authManager->hasItemChild($role->name, $operation)) {
					Yii::app()->authManager->addItemChild($role->name, $operation);
				}
			}
			return true;
		}
	}

}
